<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .div1 {
            width: 500px;
            height: 500px;
            background-color: hotpink;
        }
    </style>
</head>
<body>
    <div class="div1"></div>
    <script>
        var touchEvent = {
            longTap(el, fn) {
                var startX, startY;
                var timer = null;
                el.addEventListener('touchstart', function(e) {
                    if(timer) {
                        clearTimeout(timer);
                        timer = null
                    }
                    // console.log(e.touches[0].clientX);
                    // 获取初始化的坐标
                    startX = e.touches[0].clientX;
                    startY = e.touches[0].clientY;
                    // console.log('按下还是长按？');
                    timer = setTimeout(function() {
                        // 如果是拖拽就不执行longtap事件对应的代码
                        // console.log(e.touches[0].clientX);
                        // console.log(startX);
                        fn()
                        console.log('长按');
                    }, 750)
                    // 阻止默认事件
                    e.preventDefault();
                }, false)
                el.addEventListener('touchmove', function(e) {
                    var endX = e.touches[0].clientX;
                    var endY = e.touches[0].clientY;
                    console.log(startX);
                    console.log(endX);
                    if(timer && Math.abs(endX-startX) > 10 || Math.abs(endY-startY) > 10) {
                        // 清除定时器，目的是不执行longtap的代码
                        clearTimeout(timer);
                        timer = null
                        console.log('move了。。');
                    }
                })
                el.addEventListener('touchend', function() {
                    if(timer) {
                        clearTimeout(timer);
                        timer = null
                    }
                })
            }
        }

        window.onload = function() {
            var div = document.querySelector('.div1');
            touchEvent.longTap(div, function() {
                div.innerHTML = 'longTap'
            })
        }
    </script>
</body>
</html>